import { createLogger } from './logger'

const logger = createLogger('Emitter')
class Emitter {
  listeners = {} as { [key: string]: Fn[] }

  on(name: string, fn: Fn) {
    if (!this.listeners[name]) {
      this.listeners[name] = []
    }
    const exists = this.listeners[name].find((listener) => listener === fn)
    !exists && this.listeners[name].push(fn)

    return this
  }

  off(name: string, fn?: Fn) {
    if (fn) {
      this.listeners[name] = this.listeners[name].filter(
        (listener) => listener !== fn,
      )
    } else {
      this.listeners[name] = []
    }
  }

  once(name: string, fn: Fn) {
    const wrapFn = (...args: any[]) => {
      fn(...args)
      this.off(name, wrapFn)
    }

    return this.on(name, wrapFn)
  }

  emit(name: string, ...args: any[]) {
    logger.info('emit event:', name)
    if (this.listeners[name]) {
      this.listeners[name].forEach((listener) => listener(...args))
    }
  }
}

const eventEmitter = new Emitter()

export { eventEmitter }
